/**
 * Created by zj 2018/3/30.
 */

$(document).ready(function () {
    /*    document.write("<script language='javascript' src='paged.js'></script>");*/

    //获取页面的高度和宽度
    var sWidth = document.body.scrollWidth;
    var sHeight = document.body.scrollHeight;

    //获取页面的可视区域高度和宽度
    var wHeight = document.documentElement.clientHeight;

    //创建模糊层div
    var oMask = document.createElement("div");
    oMask.id = "mask";
    oMask.style.height = sHeight + "px";
    oMask.style.width = sWidth + "px";

    var maxDiv = document.createElement("div");
    maxDiv.id = 'maxDiv';

    var firstContent = '<div id="close">点击关闭</div>' +
        '<button id="editCellButton">修改单元格</button>' +
        '<button id="deleteRowColButton">删除行和列</button>';

    var secondContent = '<div id="close">点击关闭</div>' +
        '<div id="editCell"> ' +
        '<span id="title1">修改单元格</span><br><span id="title2">（如果想删除，则新值栏不填。）</span>' +
        '<input id="rowNo" class="editParam" type="text" placeholder="行号：">' +
        '<span id="promptRow"></span><br> ' +
        '<input id="colName" class="editParam" type="text" placeholder="列名：">' +
        '<span id="promptCol"></span><br> ' +
        '<input id="newValue" class="editParam" type="text" placeholder="新值：">' +
        '<span id="promptNewValue"></span><br><br> ' +
        '<input id="editButton" type="button" value="确认修改"></input>' +
        '</div> ';

    var thirdContent = '<div id="close">点击关闭</div>' +
        '<div id="deleteRC"><p>行和列可同时删除</p>' +
        '<input id="rowCheckbox" type="checkbox" name="deleteRowOrCol"> ' +
        '<input id="deleteRowId" class="deleteRowOrCol" type="text" disabled=true placeholder="行号：">' +
        '<span id="promptRow"></span><br> ' +
        '<input id="colCheckbox" type="checkbox" name="deleteRowOrCol"> ' +
        '<input id="deleteColId" class="deleteRowOrCol" type="text" disabled=true placeholder="列名：">' +
        '<span id="promptCol"></span><br><br> ' +
        '<button id="deleteButton">确认删除</button> </div>';

    $('#editFile').click(function () {
        firstWindow();
        return false;
    });

    function firstWindow() {
        document.body.appendChild(oMask);
        maxDiv.innerHTML = firstContent;
        document.body.appendChild(maxDiv);
        /*这四句代码必须放在下面，否则无效，可能是因为插入body中才有下面的几个属性。*/
        //获取登陆框的宽和高
        var dHeight = maxDiv.offsetHeight;
        var dWidth = maxDiv.offsetWidth;
        //设置登陆框的left和top
        //页面宽度减去登录框宽度除以2就是登录框的左外边距
        maxDiv.style.left = sWidth / 2 - dWidth / 2 + "px";
        maxDiv.style.top = wHeight / 2 - dHeight / 2 + "px";
        /*
         注意，firstContent是在此方法中插入body的，所以editCellButton这个id是局部变量，
         所以其click时间要写在此方法里面
         */
        $('#editCellButton').click(function () {
            document.body.removeChild(maxDiv);
            document.body.removeChild(oMask);
            secondWindow();
        });

        $('#deleteRowColButton').click(function () {
            document.body.removeChild(maxDiv);
            document.body.removeChild(oMask);
            thirdWindow();
        });

        /*
         close这个id是局部变量，所以其click时间要写在此方法里面
         */
        $('#close').click(function () {
            document.body.removeChild(maxDiv);
            document.body.removeChild(oMask);
        });

    }


    function secondWindow() {
        document.body.appendChild(oMask);
        maxDiv.innerHTML = secondContent;
        document.body.appendChild(maxDiv);
        //获取登陆框的宽和高
        var dHeight = maxDiv.offsetHeight;
        var dWidth = maxDiv.offsetWidth;
        //设置登陆框的left和top
        //页面宽度减去登录框宽度除以2就是登录框的左外边距
        maxDiv.style.left = sWidth / 2 - dWidth / 2 + "px";
        maxDiv.style.top = wHeight / 2 - dHeight / 2 + "px";

        $('#rowNo').blur(function () {
            verifyRow();
        });

        $('#colName').blur(function () {
            verifyCol();
        });

        $('#newValue').blur(function () {
            verifyNewValut();
        });

        //虽然secondWindow()和thirdWindow()都用到了$('#colName').blur和$('#rowNo').blur，
        //但是所选择的元素是局部变量，所以不能封装出去。
        function verifyRow() {
            var prompt = '不能为空';
            var content = '没有该行';
            var rowNo = $('#rowNo').val();
            var pattern = /^0*[1-9]\d*$/;

            if (rowNo == '') {
                $('#promptRow').empty();
                $('#promptRow').append(prompt);
                return false;
            } else if (!pattern.test(rowNo)) {//不能用null判读
                $('#promptRow').empty();
                $('#promptRow').append(content);
                return false;
            } else {
                $('#promptRow').empty();
                return true;
            }
        }

        function verifyCol() {
            var prompt = '不能为空';
            var content = '没有该列';
            var colName = $('#colName').val();
            var pattern = /^A[1-9]$|^A1[0-2]$|^quality$/;
            if (colName == '') {
                $('#promptCol').empty();
                $('#promptCol').append(prompt);
                return false;
            } else if (!pattern.test(colName)) {//不能用null判读
                $('#promptCol').empty();
                $('#promptCol').append(content);
                return false;
            } else {
                $('#promptCol').empty();
                return true;
            }
        }

        function verifyNewValut() {
            var content = '请输入数值';
            var colName = $('#colName').val();
            var newValue = $('#newValue').val();
            var pattern = /^\d+.*\d+$/;
            if (colName != 'quality' && newValue != '' && !pattern.test(newValue)) {//不能用null判读
                $('#promptNewValue').empty();
                $('#promptNewValue').append(content);
                return false;
            } else {
                $('#promptNewValue').empty();
                return true;
            }
        }

        /*
         注意，secondContent是在此方法中插入body的，所以editButton这个id是局部变量，
         所以其click时间要写在此方法里面
         */
        $('#editButton').click(function () {
            var rowNo = $('#rowNo').val();
            var colName = $('#colName').val();
            var newValue = $('#newValue').val();

            var flag1 = verifyRow();
            var flag2 = verifyCol();
            var flag3 = verifyNewValut();

            if (flag1 && flag2 && flag3) {
                document.body.removeChild(maxDiv);
                document.body.removeChild(oMask);
                editCell(rowNo, colName, newValue);
            }
        });
        /*
         close这个id是局部变量，所以其click时间要写在此方法里面
         */
        $('#close').click(function () {
            document.body.removeChild(maxDiv);
            document.body.removeChild(oMask);
        });
    }

    //虽然secondWindow()和thirdWindow()都用到了$('#colName').blur和$('#rowNo').blur，
    //但是所选择的元素是局部变量，所以不能封装出去。
    function thirdWindow() {
        document.body.appendChild(oMask);
        maxDiv.innerHTML = thirdContent;
        document.body.appendChild(maxDiv);
        //获取登陆框的宽和高
        var dHeight = maxDiv.offsetHeight;
        var dWidth = maxDiv.offsetWidth;
        //设置登陆框的left和top
        //页面宽度减去登录框宽度除以2就是登录框的左外边距
        maxDiv.style.left = sWidth / 2 - dWidth / 2 + "px";
        maxDiv.style.top = wHeight / 2 - dHeight / 2 + "px";

        /*
         复选框模块
         */
        var isCheckedRow = true;
        var isCheckedCol = true;
        $('#rowCheckbox').change(function () {
            isCheckedRow = !isCheckedRow;
            $('#deleteRowId').attr('disabled', isCheckedRow);
        });
        $('#colCheckbox').change(function () {
            isCheckedCol = !isCheckedCol;
            $('#deleteColId').attr('disabled', isCheckedCol);
        });

        //虽然secondWindow()和thirdWindow()都用到了$('#colName').blur和$('#rowNo').blur，
        //但是所选择的元素是局部变量，所以不能封装出去。
        $('#deleteRowId').blur(function () {
            verifyRowDelete();
        });

        function verifyRowDelete() {
            var content = '没有该行';
            var rowNo = $('#deleteRowId').val();
            var pattern = /^0*[1-9]\d*$/;

            if (rowNo != '' && !pattern.test(rowNo)) {
                $('#promptRow').empty();
                $('#promptRow').append(content);
                return false;
            } else {
                $('#promptRow').empty();
                return true;
            }
        }

        $('#deleteColId').blur(function () {
            verifyColDelete();
        });

        function verifyColDelete() {
            var content = '没有该列';
            var colName = $('#deleteColId').val();
            var pattern = /^A[1-9]$|^A1[0-2]$|^quality$/;

            if (colName != '' && !pattern.test(colName)) {
                $('#promptCol').empty();
                $('#promptCol').append(content);
                return false;
            } else {
                $('#promptCol').empty();
                return true;
            }
        }

        /*
         提交删除按钮模块
         */
        $('#deleteButton').click(function () {
            var rowNo = $('#deleteRowId').val();
            var colName = $('#deleteColId').val();

            var flag1 = verifyRowDelete();
            var flag2 = verifyColDelete();

            if (rowNo != '' && colName != '' && flag1 && flag2) {
                document.body.removeChild(maxDiv);
                document.body.removeChild(oMask);
                deleteRowAndCol(rowNo, colName);
            }

            //如果两栏都填了但只有一栏满足条件则不单独执行，
            // 如果向同时删除行和列就要两者都符合条件才能一起执行
            if (rowNo != '' && colName != '')
                return;

            if (flag1 && rowNo != '') {
                document.body.removeChild(maxDiv);
                document.body.removeChild(oMask);
                deleteRow(rowNo);
            }
            if (flag2 && colName != '') {
                document.body.removeChild(maxDiv);
                document.body.removeChild(oMask);
                deleteCol(colName);
            }

        });

        /*
         close这个id是局部变量，所以其click时间要写在此方法里面
         */
        $('#close').click(function () {
            document.body.removeChild(maxDiv);
            document.body.removeChild(oMask);
        });
    }

    /*
     oMask和id选择器不同，oMask属于全局变量
     */
    oMask.onclick = function () {
        document.body.removeChild(maxDiv);
        document.body.removeChild(oMask);
    }

    function editCell(rowNo, colName, newValue) {
        $.ajax({
            url: 'editCellInFile.do',
            type: 'POST',
            cache: false,
            async: false,
            data: {"rowNo": rowNo, "colName": colName, "newValue": newValue},
            error: function (XMLHttpRequest, textStatus) {
                alert(XMLHttpRequest.status);
                alert(XMLHttpRequest.readyState);
                alert(textStatus);
                alert('修改失败！');
            },
            success: function (result) {
                if (result == 'success')
                    alert('修改成功！');
                else if (result == 'notExists')
                    alert('文件不存在');
                else if (result == 'fileIsEmpty')
                    alert('文件为空');
                else if (result == 'theColAlreadyDeleted')
                    alert('该列已被删除');
                else if (result == 'spaceInFileTop')
                    alert('文件顶部有空格');
                else if (result == 'notExistsTheRow')
                    alert('不存在此行');
                else
                    alert('修改失败');
            }
        });
    }

    function deleteRowAndCol(rowNo, colName) {
        $.ajax({
            url: 'deleteRowAndCol.do',
            type: 'POST',
            cache: false,
            async: false,
            data: {"rowNo": rowNo, "colName": colName},
            error: function (XMLHttpRequest, textStatus) {
                alert(XMLHttpRequest.status);
                alert(XMLHttpRequest.readyState);
                alert(textStatus);
                alert('请求失败！');
            },
            success: function (result) {
                var result1 = result.split(',')[0];
                var result2 = result.split(',')[1];

                if (result1 == 'success')
                    alert('删除第' + rowNo + '行成功！');
                else if (result1 == 'notExists')
                    alert('文件不存在');
                else if (result1 == 'fileIsEmpty')
                    alert('文件为空');
                else if (result1 == 'spaceInFileTop')
                    alert('文件顶部有空格');
                else if (result1 == 'notExistsTheRow')
                    alert('不存在此行');
                else
                    alert('删除失败');

                if (result2 == 'success')
                    alert('删除' + colName + '列成功！');
                else if (result2 == 'notExists')
                    alert('文件不存在');
                else if (result2 == 'theColAlreadyDeleted')
                    alert('该列已被删除');
                else if (result2 == 'spaceInFileTop')
                    alert('文件顶部有空格');
                else
                    alert('删除失败');
            }
        });
    }

    function deleteRow(rowNo) {
        $.ajax({
            url: 'deleteRow.do',
            type: 'POST',
            cache: false,
            async: false,
            data: {"rowNo": rowNo},
            error: function (XMLHttpRequest, textStatus) {
                alert(XMLHttpRequest.status);
                alert(XMLHttpRequest.readyState);
                alert(textStatus);
                alert('删除失败！');
            },
            success: function (result) {
                if (result == 'success')
                    alert('删除第' + rowNo + '行成功！');
                else if (result == 'notExists')
                    alert('文件不存在');
                else if (result == 'fileIsEmpty')
                    alert('文件为空');
                else if (result == 'spaceInFileTop')
                    alert('文件顶部有空格');
                else if (result == 'notExistsTheRow')
                    alert('不存在此行');
                else
                    alert('删除失败');
            }
        });
    }

    function deleteCol(colName) {
        $.ajax({
            url: 'deleteCol.do',
            type: 'POST',
            cache: false,
            async: false,
            data: {"colName": colName},
            error: function (XMLHttpRequest, textStatus) {
                alert(XMLHttpRequest.status);
                alert(XMLHttpRequest.readyState);
                alert(textStatus);
                alert('删除失败！');
            },
            success: function (result) {
                if (result == 'success')
                    alert('删除' + colName + '列成功！');
                else if (result == 'notExists')
                    alert('文件不存在');
                else if (result == 'theColAlreadyDeleted')
                    alert('该列已被删除');
                else if (result == 'spaceInFileTop')
                    alert('文件顶部有空格');
                else
                    alert('删除失败');
            }
        });
    }

});
